<?php
/**
 * Created by PhpStorm.
 * User: xuyiping
 * Date: 2018/7/5
 * Time: 11:26
 */
namespace app\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Libraries\Small\WxSmallService;
use App\Model\RoomPercentageModel;
use Symfony\Component\HttpFoundation\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Admin\GoldController;
use App\Http\Controllers\Api\ApiMainController;
use App\Model\GoldBeanModel;
use App\Model\PkRecordModel;
use App\Model\WebUserModel;
use App\Model\RelfriendModel;
class ApiPkController extends ApiMainController{

    //检查金币数
    public function checkGold(){
        if($this->_defalutJson['code']==-1 && empty($this->userId)){
            return  response()->json(array(
                'code'    => 404,
                'message' => $this->_defalutJson['message'],
            ));
        }
        $gold = GoldBeanModel::select('iUserId','iNowGoldBean')
            ->where("iUserId",$this->userId)
            ->get()
            ->toArray();

        if(empty($gold)) {
            return  response()->json(array(
                'code' => 400,
                'message' => "数据查询失败，请重试！！",
                'data' => ['uuid'=>$this->uuid],
            ));
            //exit;
        }
        //查询房费比例
        $data = DB::table('room_percentage')->get()->toArray();
        $data=array_map('get_object_vars', $data);
        return  response()->json(array(
            'code' => 200,
            'message' => "数据查询成功",
            'data' =>array(
                'gold'          => $gold[0]['iNowGoldBean'],
                'uuid'          => $this->uuid,
                'roomFeeprcent' => empty($data[0]['percentage']) ? 0 :$data[0]['percentage'], //房费比例
            ),
        ));
    }
    /*
     * 检查pk
     * */
    public function checkPkApi(Request $request){
        if($this->_defalutJson['code']==-1 && empty($this->userId)){
            return  response()->json(array(
                'code'    => 404,
                'message' => $this->_defalutJson['message'],
            ));
        }
        $iSeqId=  $request->input('iSeqId');//数据的流水
        if(empty($iSeqId)){
            return  response()->json(array(
                'code'    => 400,
                'message' => "缺少参数",
                "data"    => ['uuid'=>$this->uuid]
            ));
        }

        $pkdata= PkRecordModel::where(function($query ) use ($iSeqId){
                $query->where([
                    "iUserId"     => $this->userId,
                    "sInitiative" => 1,
                    "iSeqId"      => $iSeqId,
                    'iStatus'    =>1
                ]);
            })->get()->toArray();

        if(!empty($pkdata)){
            if($pkdata[0]['iOpponentId']==0){
                return  response()->json(array(
                    'code'    => 400,
                    'message' => "还没有对手加入",
                    "data"    => []
                ));
            }else{
                return  response()->json(array(
                    'code'    => 200,
                    'message' => "对手加入成功",
                    "data"    => ['uuid'=>$this->uuid,
                     'iSeqId' =>$iSeqId,]
                ));
            }
        }else{
            return  response()->json(array(
                'code'    => 404,
                'message' => "数据不存在",
                "data"    => []
            ));
        }
    }
    /*
    * 检查pk
    * */
    public function recgetmasterApi(Request $request){
        if($this->_defalutJson['code']==-1 && empty($this->userId)){
            return  response()->json(array(
                'code'    => 404,
                'message' => $this->_defalutJson['message'],
            ));
        }
        $iSeqId=  $request->input('iSeqId');//数据的流水
        if(empty($iSeqId)){
            return  response()->json(array(
                'code'    => 400,
                'message' => "缺少参数",
                "data"    => ['uuid'=>$this->uuid]
            ));
        }

        $pkdata= PkRecordModel::where([
                "iSeqId"     => $iSeqId,
                'iStatus'    =>1
            ])->get()->toArray();

        if($pkdata){
            $userInfo=WebUserModel::where('iSeqId',$pkdata[0]['iUserId'])->first();
            return  response()->json(array(
                'code'    => 200,
                'message' => "信息查询成功",
                "data"    => [
                    'uuid'=>$this->uuid,
                    'iSeqId' =>$iSeqId,
                    'gold' =>$pkdata[0]['sGold'],
                    'mastername' =>empty($userInfo->sUserName) ?  '' : htmlspecialchars(urldecode($userInfo->sUserName)),
                    'masterimage' =>empty($userInfo->sUserImage) ?  '' : $userInfo->sUserImage,
                ]
            ));
        }else{
            return  response()->json(array(
                'code'    => 404,
                'message' => "数据不存在",
                "data"    => []
            ));
        }
    }

    /*
     * 添加创建pk
     * */
    public function addPkApi(Request $request){
        //检查用户
        if($this->_defalutJson['code']==-1 && empty($this->userId)){
            return  response()->json(array(
                'code'    => 404,
                'message' => $this->_defalutJson['message'],
            ));
        }

        $sGold       = $request->input('sGold');//押豆数量
        $sPkType     = $request->input('sPkType');//pK类型 5/3 ，9/5
        $iPkWaitTime = date("Y-m-d H:i:s");//pK类型 5/3 ，9/5

        //执行插入

        if(empty($sGold) || $sGold<100){
            return  response()->json(array(
                'code' => 400,
                'message' => '请选择金豆数,并且不能小于100！！',
            ));
        }
        if(empty($sPkType)){
            return  response()->json(array(
                'code' => 400,
                'message' => '请选择PK类型！！',
            ));
        }

        //查询是否已存在有效的数据

        $pkdata= PkRecordModel::select('iUserId','iSeqId')
            ->where(function($query){
                $query->where(array("iUserId"=>$this->userId,"iOpponentId"=>0,"sInitiative"=>1,"iStatus"=>1))
                //$query->where(array("iOpponentId"=>NUll,"sInitiative"=>1,"iStatus"=>1));
                        ->where("iPkWaitTime",'>',date("Y-m-d H:i:s",time()-15*60));
                        //->where("iPkWaitTime",'>',date("Y-m-d H:i:s",time()-1*60));
            })
            ->get()
            ->toArray();
        if(!empty($pkdata)){
            return  response()->json(array(
                'code' => 400,
                'message' => "您已创建对局，请重试！！",
                'data' => array(
                    'uuid'=>$this->uuid
                ),
            ));
        }
        //开房消耗金豆
        $data = DB::table('room_percentage')->get()->toArray();
        $data = array_map('get_object_vars', $data);
        $percent = empty($data[0]['percentage']) ? 0 : $data[0]['percentage'];

        $sGoldAll = 0;
        if(!empty($percent)){
            $percentGold = ceil($sGold*($percent/100));
            $sGoldAll = $sGold + ceil($percentGold/2);//扣除金豆总数
        }

        //检查是否有足够的金豆
        $checkgold = GoldBeanModel::select('iUserId','iNowGoldBean')
            ->where("iUserId",$this->userId)
            ->get()
            ->toArray();

        if(empty($checkgold)) {
            return  response()->json(array(
                'code' => 404,
                'message' => "数据异常，请重试！！",
                'data' => ['uuid'=>$this->uuid],
            ));

        }else{
            $bean=empty($checkgold[0]['iNowGoldBean']) ? '' : $checkgold[0]['iNowGoldBean'];
            if( $bean < $sGoldAll){
                $goldModel=new GoldController();
                //$result=$goldModel->exChangeGold(-$sGoldAll,$this->userId,2);
                return  response()->json(array(
                    'code' => 400,
                    'message' => "账户的金豆数不足！！",
                    'data' => ['uuid'=>$this->uuid],
                ));
            }
        }

        $addArray = array();
        $addArray['iUserID']     = $this->userId;
        $addArray['sGold']       = $sGold;
        $addArray['iPkWaitTime'] = $iPkWaitTime;
        $addArray['sModifyUser'] = $this->userId;
        $addArray['sInitiative'] = 1;//是否主动  1 就是主动 0 被动
        $addArray['sPkType']     = $sPkType;//pk类型

        $bool = DB::table('pkrecord')->insertGetId($addArray);

        if(!empty($bool)){
            return  response()->json(array(
                'code' => 200,
                'message' => 'pk创建成功，等待对手加入！！',
                'data'=>[
                    'iPkWaitTime' => $iPkWaitTime,//pk等待时间
                    'iSeqId'      =>$bool,//数据ID
                    'sGold'       =>$sGold,//数据ID
                    'sPkType'     =>$sPkType,//数据ID
                    'uuid'        =>$this->uuid
                ]
            ));
        }
        return  response()->json(array(
            'code' => -1,
            'message' => '未知错误！！',
        ));
    }

    //等待PK页获取access_token
    public function waitPkApi(Request $request){

        header('content-type:image/png');
        $uuid = $request->input('uuid');
        $path = $request->input('path');
        $iSeqId = $request->input('pk_id');
        $scene = $request->input('scene');

        if(!isset($uuid) || empty($uuid)){
            return response()->json(array('code' => 400,'message' => 'uuid值不能为空'));
        }

        if(!isset($path) || empty($path)){
            return response()->json(array('code' => 400,'message' => '请传跳转路径'));
        }

        $user_data = WebUserModel::where('iUUID',$uuid)->first();
        if(!$user_data){
            return response()->json(array('code' => 400,'message' => '该用户不存在'));
        }

        $pk_data = PkRecordModel::where('iSeqId',$iSeqId)->first();
        if(!$pk_data){
            return response()->json(array('code' => 400,'message' => '该PK不存在'));
        }
        //获取微信的access——token
        $get_access_token = WxSmallService::get_access_token();
        if($get_access_token['code'] == 200){

            $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$get_access_token['data']['access_token'];
            $option_json = json_encode([
                'scene'      => !empty($scene) ? $scene : 'empty',
                'page'       => $path,
                'auto_color' => false,
                'line_color' => (object)['r'=>0,'g'=>0,'b'=>0],
                'is_hyaline' => false,
                'width'      => '430'
            ]);
            $src_data = WxSmallService::api_notice_increment($url,$option_json);

            $path_file = '/usr/local/nginx/html/xinmo_master/public';
            $path_name = '/image/qrcode/'.date('Ymd').'/';

            $file_name = date('YmdHis').rand(1000,9000).'.png';

            if(!file_exists($path_file.$path_name)){
                mkdir($path_file.$path_name, 0777 ,true);
            }
            $file = $path_file.$path_name. $file_name;
            file_put_contents($file,$src_data);

            PkRecordModel::where('iSeqId',$iSeqId)->update(['sCode'=>$path_name.$file_name]);

            return response()->json(array('code' => 200,'message' => '成功','data'=>['src'=>$_SERVER['SERVER_NAME'].$path_name.$file_name]));
        }else{
            return response()->json(array('code' => 400,'/' => '获取小程序二维码失败'));
        }
    }

    /*
     * 取消pK
     * */
    public function cancelPkApi(Request $request){
        if($this->_defalutJson['code']==-1 && empty($this->userId)){
            return  response()->json(array(
                'code'    => 404,
                'message' => $this->_defalutJson['message'],
            ));
        }
        $iSeqId=  $request->input('iSeqId');//数据的流水
        if(empty($iSeqId)){
            return  response()->json(array(
                'code'    => 400,
                'message' => "缺少参数",
                "data"    => ['uuid'=>$this->uuid]
            ));
        }

        $pkdata= PkRecordModel::select('iUserId','iSeqId')
            ->where(function($query ) use ($iSeqId){
                $query->where([
                    "iUserId"     => $this->userId,
                    "iOpponentId" => 0,
                    "sInitiative" => 1,
                    "iSeqId"      => $iSeqId,
                    'iStatus'    =>1
                ]);
            })->get()->toArray();

        if(!empty($pkdata)){
            PkRecordModel::where("iSeqId",$iSeqId)->update(['iStatus'=>'-1']);//状态置为-1 代表取消
        }
        return  response()->json(array(
            'code'    => 200,
            'message' => "取消成功",
            "data"    => ['uuid'=>$this->uuid]
        ));

    }

    /*
     * 接受PK
     * */
    public function recivePkApi(Request $request){

        if($this->_defalutJson['code']==-1 && empty($this->userId)){
            return  response()->json(array(
                'code'    => 404,
                'message' => $this->_defalutJson['message'],
            ));
        }
        //验证参数
        $iSeqId = $request->input('iSeqId');//数据的流水
        if(empty($iSeqId)){
            return  response()->json(array(
                'code' => 404,
                'message' => "缺少参数",
                "data"=>['uuid'=>$this->uuid]
            ));
        }
        //验证数据是否存在
        //$datapk = DB::table('pkrecord')
        $datapk = PkRecordModel::where([
                 'iSeqId'      =>$iSeqId,
                 'iStatus'     =>1,
                 "iOpponentId" =>0
             ])->get()->toArray();

        //$datapk = array_map('get_object_vars', $data);
        if(empty($datapk)){
            return  response()->json(array(
                'code'    => 404,
                'message' => '对局不存在，请重新扫码进入！！',
            ));
        }
        //
        //开房消耗金豆
        //$data = DB::table('room_percentage')->get()->toArray();
        //$data=array_map('get_object_vars', $data);
        $data = RoomPercentageModel::get()->toArray();
        $percent=empty($data[0]['percentage']) ? 0 : $data[0]['percentage'];

        if(!empty($percent)){
            $percentGold=ceil($datapk[0]['sGold']*($percent/100));
            $sGoldAll=$datapk[0]['sGold']+ceil($percentGold/2);//扣除金豆总数
        }
        //检查是否有足够的金豆
        $checkgold = GoldBeanModel::select('iUserId','iNowGoldBean')->where("iUserId","=",$this->userId)->get()->toArray();
        if(empty($checkgold)) {
            return  response()->json(array(
                'code' => 404,
                'message' => "数据异常，请重试！！",
                'data' => ['uuid'=>$this->uuid],
            ));
            //exit;
        }else{
            $bean=empty($checkgold[0]['iNowGoldBean'])? '' : $checkgold[0]['iNowGoldBean'];
            if( $bean < $sGoldAll){
                $goldModel=new GoldController();
                //$result=$goldModel->exChangeGold(-$sGoldAll,$this->userId,2);
                return  response()->json(array(
                    'code' => 400,
                    'message' => "账户的金豆数不足！！",
                    'data' => ['uuid'=>$this->uuid],
                ));
            }

        };
       //修改发起人对局记录信息
         $num = DB::table('pkrecord')
          ->where('iSeqId','=',$iSeqId)
          ->update(array('iOpponentId'=>$this->userId));
            if($num>=1){
                //获取对局信息
                $userIdin=array($datapk[0]['iUserId'],$this->userId);
                $userInfo=WebUserModel::whereIn('iSeqId',$userIdin)->get()->toarray();
                $temdata=array();
                foreach($userInfo as &$value){
                    $value['sUserName']=htmlspecialchars(urldecode($value['sUserName']));
                    if($value['iSeqId']==$datapk[0]['iUserId']){
                        $temdata['masterone']=$value;
                        //$temdata['masterone']['']=$value;
                    }else{
                        $temdata['mastertwo']=$value;
                    }
                }
                return  response()->json(array(
                    'code' => 200,
                    'message' => '对局加入成功！！',
                    'data'=>array(
                        'iSeqId' =>$iSeqId,//数据流水
                        'uuid'=>$this->uuid,
                        'sPkType'=>$datapk[0]['sPkType'],
                        'list'=>$temdata,
                    ),
                ));
            }
        return  response()->json(array(
            'code' => 400,
            'message' => '未知错误！！',
        ));
    }
    /*
     * 开始对局
     * */
    public function addApi(Request $request){
        if($this->_defalutJson['code']==-1 && empty($this->userId)){
            return  response()->json(array(
                'code' => 404,
                'message' => $this->_defalutJson['message'],
            ));
        }
        $iSeqId=  $request->input('iSeqId');//流水
        if(empty($iSeqId)){
            return  response()->json(array(
                'code' => 404,
                'message' => "缺少参数",
                "data"=>['uuid'=>$this->uuid]
            ));
        }

        $data = DB::table('pkrecord')
            ->where('iSeqId','=',$iSeqId)
            ->get()->toArray();
        $data=array_map('get_object_vars', $data);
        if(empty($data)) {
            return  response()->json(array(
                'code' => 404,
                'message' => "没有数据！！",
                'data' => ['uuid'=>$this->uuid],
            ));//exit;
        }
        if(empty($data[0]['iOpponentId'])){
            return  response()->json(array(
                'code' => -1,
                'message' => '还没有对手加入请等待！！',
            ));
        }
        //修改发起人对局记录信息
        $num = DB::table('pkrecord')
            ->where('iSeqId','=',$iSeqId)
            ->update(array('dtStartTime'=>date("Y-m-d H:i:s")));
        //添加对手记录表

        $dataOne = DB::table('relfriend')->where('master_user_id','=',$this->userId)->where('user_id','=',$data[0]['iOpponentId'])->get()->toArray();
        $dataOne=array_map('get_object_vars', $dataOne);
        if(empty($dataOne)) {
            $bool = DB::table('relfriend')->insertGetId(array("master_user_id"=>$this->userId,"user_id"=>$data[0]['iOpponentId'],"dtCommitTime"=>date("Y-m-d H:i:s"),"iAllPk"=>0));
        }else{
           //$num = DB::table('relfriend')->where(array('iSeqId'=>$dataOne[0]['iSeqId']))->increment('iAllPk',1);
        }

        $dataTwo = DB::table('relfriend')->where('master_user_id','=',$data[0]['iOpponentId'])->where('user_id','=',$this->userId)->get()->toArray();
        $dataTwo=array_map('get_object_vars', $dataTwo);
        if(empty($dataTwo)) {
            $bool = DB::table('relfriend')->insertGetId(array("master_user_id"=>$data[0]['iOpponentId'],"user_id"=>$this->userId,"dtCommitTime"=>date("Y-m-d H:i:s"),"iAllPk"=>0));
        }else{
            //$num = DB::table('relfriend')->where(array('iSeqId'=>$dataTwo[0]['iSeqId']))->increment('iAllPk',1);
        }


        //获取对局双方信息
        $userIdin=array($data[0]['iUserId'],$data[0]['iOpponentId']);
        $userInfo=WebUserModel::whereIn('iSeqId',$userIdin)->get()->toarray();
        $temdata=array();
        foreach($userInfo as &$value){
            $value['sUserName']=htmlspecialchars(urldecode($value['sUserName']));
            if($value['iSeqId']==$data[0]['iUserId']){

                $temdata['masterone']=$value;
                $temdata['masterone']['sPkType']=$data[0]['sPkType'];
                $temdata['masterone']['gold']=$data[0]['sGold'];
            }else{
                $temdata['mastertwo']=$value;
                $temdata['mastertwo']['sPkType']=$data[0]['sPkType'];;
                $temdata['mastertwo']['gold']=$data[0]['sGold'];
            }
        }
        return  response()->json(array(
            'code' => 200,
            'message' => '查询成功！！',
            'data' => array(
                'iSeqId' =>$iSeqId,//数据流水
                'uuid'=>$this->uuid,
                'dtStartTime'=>date("Y-m-d H:i:s"),//对局开始时间
                'list'=>$temdata,
            ),
        ));
    }
    /*
     * PK结果
     */
    public function resultPkApi(Request $request){
        if($this->_defalutJson['code']==-1 && empty($this->userId)){
            return  response()->json(array(
                'code' => 404,
                'message' => $this->_defalutJson['message'],
            ));
        }
        $iSeqId=  $request->input('iSeqId');//流水
        if(empty($iSeqId)){
            return  response()->json(array(
                'code' => 404,
                'message' => "缺少参数",
                "data"=>['uuid'=>$this->uuid]
            ));
        }
        $data = DB::table('pkrecord')
            ->where(array('iSeqId'=>$iSeqId))
            ->get()->toArray();
        $data=array_map('get_object_vars', $data);
        if(empty($data)){
            return  response()->json(array(
                'code' => 404,
                'message' => '对局不存在,请稍后重试！！',
            ));
        };
        if(empty($data[0]['iOpponentId'])){
            return  response()->json(array(
                'code' => 404,
                'message' => '对局缺少对手！！',
            ));
        };
        if($data[0]['iUserId']==$this->userId){
            if($data[0]['iStatus'] == 2){
                return  response()->json(array(
                    'code' => 404,
                    'message' => '请勿重复提交数据！！',
                ));
            };
        };
        //验证时间 防止过早提交
        if(!empty($data[0]['dtStartTime'])){
            if($data[0]['sPkType']==1) $minte=60*9 ;
            if($data[0]['sPkType']==2) $minte=60*15;
            if(time()-strtotime($data[0]['dtStartTime'])< $minte){
                return  response()->json(array(
                    'code' => 400,
                    'message' => '对局提交过早，请稍后提交！！',
                    'data' => date("Y-m-d H;i:s"),
                ));
            }
            $chatime=time()-strtotime($data[0]['dtStartTime']);
        }
        $sGan=$request->input('sGan');
        $sGan=   empty($sGan) ? 0 : intval($request->input('sGan'));//清杆数

        //
        //$this->userId=13;
        if($data[0]['iUserId']==$this->userId){
            //验证比分
            $sScore=   $request->input('sScore');//比分

            $iResult=-2;
            $sExt=array();
            $iStatus=2;

            if($data[0]['sPkType']==1){
                $sScore=explode('-',$sScore);
                /*var_dump(is_array($sScore));
                var_dump(count($sScore)!= 2);*/
                //exit;
                if(!is_array($sScore) || count($sScore)!= 2){
                    return  response()->json(array(
                        'code' => 400,
                        'message' => '对局比分格式错误请重新提交！！',
                    ));
                }

                if($sScore[0]+$sScore[1] >5){
                    return  response()->json(array(
                        'code' => 400,
                        'message' => '对局比分错误请重新提交！！',
                    ));
                }
                if($sScore[0]>3 || $sScore[1]>3){
                    return  response()->json(array(
                        'code' => 400,
                        'message' => '对局比分错误请重新提交！！',
                    ));
                }
                if($sScore[0] < 3 && $sScore[1]< 3){
                    return  response()->json(array(
                        'code' => 400,
                        'message' => '对局比分错误请重新提交！！',
                    ));
                }
                if($sScore[0] == 3 && $sScore[1]==3){
                    return  response()->json(array(
                        'code' => 400,
                        'message' => '对局比分错误请重新提交！！',
                    ));
                }
                if($sScore[0] == $sScore[1]){
                    return  response()->json(array(
                        'code' => 400,
                        'message' => '对局比分错误请重新提交！！',
                    ));
                }

                //清杆数
                if($sGan > 3){
                    return  response()->json(array(
                        'code' => 400,
                        'message' => '清台数错误！！',
                    ));
                }
                if($sScore[0] > $sScore[1]){
                    $iResult = 1;
                }else{
                    $iResult = 0;
                }

                $sExt["sScore"]=$sScore[0].':'.$sScore[1];
                $sExt[$this->userId]=$sGan;
                $sExt['time']=$chatime;
                $iAll=$sScore[0]+$sScore[1];
                $sExt['iAll']=$iAll;

            }

            if($data[0]['sPkType']==2){
                $sScore=explode('-',$sScore);
                if(!is_array($sScore) || count($sScore)!=2){
                    return  response()->json(array(
                        'code' => 400,
                        'message' => '对局比分格式错误请重新提交！！',
                    ));
                }
                if($sScore[0]+$sScore[1] > 9){
                    return  response()->json(array(
                        'code' => 400,
                        'message' => '对局比分错误请重新提交！！',
                    ));
                }
                if($sScore[0]>5 || $sScore[1]>5){
                    return  response()->json(array(
                        'code' => 400,
                        'message' => '对局比分错误请重新提交！！',
                    ));
                }
                if($sScore[0] == 5 && $sScore[1]==5){
                    return  response()->json(array(
                        'code' => 400,
                        'message' => '对局比分错误请重新提交！！',
                    ));
                }
                if($sScore[0] < 5 && $sScore[1] < 5){
                    return  response()->json(array(
                        'code' => 400,
                        'message' => '对局比分错误请重新提交！！',
                    ));
                }

                if($sScore[0] == $sScore[1]){
                    return  response()->json(array(
                        'code' => 400,
                        'message' => '对局比分错误请重新提交！！',
                    ));
                }
                //清杆数
                if($sGan>5){
                    return  response()->json(array(
                        'code' => 400,
                        'message' => '清台数错误！！',
                    ));
                }

                if($sScore[0] > $sScore[1]){
                    $iResult = 1;
                }else{
                    $iResult = 0;
                }
                $sExt["sScore"]=$sScore[0].':'.$sScore[1];
                $sExt[$this->userId]=$sGan;
                $sExt['time']=$chatime;
                $iAll=$sScore[0]+$sScore[1];
                $sExt['iAll']=$iAll;
            }
            //判断是否超时
            if(!empty($data[0]['dtStartTime'])){
                $minte=120*60;
                if(time()-strtotime($data[0]['dtStartTime']) > $minte){
                    $iStatus=-2;
                }
            }
            //开房消耗金豆
            $datagold = DB::table('room_percentage')->get()->toArray();
            $datagold=array_map('get_object_vars', $datagold);
            $percent=empty($datagold[0]['percentage']) ? 0 : $datagold[0]['percentage'];

            if(!empty($percent)){
                $percentGold=ceil($data[0]['sGold']*($percent/100));
                $sGoldAll=ceil($percentGold/2);//扣除金豆总数
            }

            //超时操作
            if($iStatus==-2){
                $num = DB::table('pkrecord')
                    ->where('iSeqId','=',$iSeqId)
                    ->update(array('iResult'=>'0','dtEndtime'=>date("Y-m-d H:i:s"),'iStatus'=>$iStatus,"sExt"=>json_encode($sExt)));
                return  response()->json(array(
                    'code' => 400,
                    'message' => '该对局超时！！',
                    "data"=>array(
                        "uuid"=>$this->uuid
                    )
                ));
            }
            //执行扣豆操作
            if($iResult==-2){
                return  response()->json(array(
                    'code' => 400,
                    'message' => '运行错误！！',
                ));
            }
            if($iResult==0){

                $result="0-1";
                //更新数据
                $num = DB::table('pkrecord')
                    ->where('iSeqId','=',$iSeqId)
                    ->update(array('iResult'=>$result,'dtEndtime'=>date("Y-m-d H:i:s"),'iStatus'=>$iStatus,"sExt"=>json_encode($sExt)));
                $gold=new GoldController();
                $remark=array('user1'=>$this->userId,'user2'=>$data[0]['iOpponentId'],'score'=>$sExt["sScore"],'relId'=>$iSeqId);
                //主动方//增加豆子
                $gold->exChangeGold(-($sGoldAll+$data[0]['sGold']),$this->userId,2,json_encode($remark),-$data[0]['sGold']);
                //被动方
                $gold->exChangeGold(($data[0]['sGold']-$sGoldAll),$data[0]['iOpponentId'],1,json_encode($remark),$data[0]['sGold']);

                //操作朋友表
                DB::table('relfriend')->where(array('master_user_id'=>$this->userId,"user_id"=>$data[0]['iOpponentId']))->increment('iAllReward',-intval($data[0]['sGold']));
                DB::table('relfriend')->where(array('master_user_id'=>$data[0]['iOpponentId'],"user_id"=>$this->userId))->increment('iAllReward',intval($data[0]['sGold']));
                DB::table('relfriend')->where(array('master_user_id'=>$this->userId,"user_id"=>$data[0]['iOpponentId']))->increment('iAllPk',1);
                DB::table('relfriend')->where(array('master_user_id'=>$data[0]['iOpponentId'],"user_id"=>$this->userId))->increment('iAllPk',1);
                //增加人数表
                $bool = DB::table('pkpeople')->insertGetId(array("iUserID"=>$data[0]['iOpponentId'],"dtCreateTime"=>date("Y-m-d H:i:s")));
                $bool = DB::table('pkpeople')->insertGetId(array("iUserID"=>$this->userId,"dtCreateTime"=>date("Y-m-d H:i:s")));


                $bool = DB::table('pkrel')->insertGetId(array("master_userid"=>$this->userId,"userId"=>$data[0]['iOpponentId'],"pkId"=>$iSeqId,"iStatus"=>$iStatus,"iResult"=>-1,'iAll'=>$sScore[0],'izhudong'=>1,"dtTime"=>date("Y-m-d H:i:s")));
                $bool = DB::table('pkrel')->insertGetId(array("master_userid"=>$data[0]['iOpponentId'],"userId"=>$this->userId,"pkId"=>$iSeqId,"iStatus"=>$iStatus,"iResult"=>1,'iAll'=>$sScore[1],'izhudong'=>-1,"dtTime"=>date("Y-m-d H:i:s")));


                $bool = DB::table('webuser')->where(array("iSeqId"=>$data[0]['iOpponentId']))->increment("iAllWinPk",1);
            }
            if($iResult==1){
                $result="1-0";
                //更新数据
                $num = DB::table('pkrecord')
                    ->where('iSeqId','=',$iSeqId)
                    ->update(array('iResult'=>$result,'dtEndtime'=>date("Y-m-d H:i:s"),'iStatus'=>$iStatus,"sExt"=>json_encode($sExt)));
                $gold=new GoldController();

                $remark=array('user1'=>$this->userId,'user2'=>$data[0]['iOpponentId'],'score'=>$sExt["sScore"],'relId'=>$iSeqId);
                //主动方//增加豆子
                $gold->exChangeGold(($data[0]['sGold']-$sGoldAll),$this->userId,1,json_encode($remark),$data[0]['sGold']);
                //被动方
                $gold->exChangeGold(-($sGoldAll+$data[0]['sGold']),$data[0]['iOpponentId'],2,json_encode($remark),-$data[0]['sGold']);

                DB::table('relfriend')->where(array('master_user_id'=>$this->userId,"user_id"=>$data[0]['iOpponentId']))->increment('iAllReward',intval($data[0]['sGold']));
                DB::table('relfriend')->where(array('master_user_id'=>$data[0]['iOpponentId'],"user_id"=>$this->userId))->increment('iAllReward',-intval($data[0]['sGold']));
                DB::table('relfriend')->where(array('master_user_id'=>$this->userId,"user_id"=>$data[0]['iOpponentId']))->increment('iAllPk',1);
                DB::table('relfriend')->where(array('master_user_id'=>$data[0]['iOpponentId'],"user_id"=>$this->userId))->increment('iAllPk',1);
                //被动方
                //pk 人数表
                $bool = DB::table('pkpeople')->insertGetId(array("iUserID"=>$data[0]['iOpponentId'],"dtCreateTime"=>date("Y-m-d H:i:s")));
                $bool = DB::table('pkpeople')->insertGetId(array("iUserID"=>$this->userId,"dtCreateTime"=>date("Y-m-d H:i:s")));


                $bool = DB::table('pkrel')->insertGetId(array("master_userid"=>$this->userId,"userId"=>$data[0]['iOpponentId'],"pkId"=>$iSeqId,"iStatus"=>$iStatus,"iResult"=>1,'iAll'=>$sScore[0],"dtTime"=>date("Y-m-d H:i:s")));
                $bool = DB::table('pkrel')->insertGetId(array("master_userid"=>$data[0]['iOpponentId'],"userId"=>$this->userId,"pkId"=>$iSeqId,"iStatus"=>$iStatus,"iResult"=>-1,'iAll'=>$sScore[1],"dtTime"=>date("Y-m-d H:i:s")));


                $bool = DB::table('webuser')->where(array("iSeqId"=>$this->userId))->increment("iAllWinPk",1);
            }

            //操作用户表
            $bool= DB::update("update tb_webuser set iQinggan=iQinggan+".intval($sGan).",iAll=iAll+".intval($iAll).",iAllTime=iAllTime+".intval($chatime).",iAllPk=iAllPk+1" .",iWinAll=iWinAll+".$sScore[0]." where iSeqId =".$this->userId);
            $bool= DB::update("update tb_webuser set iAll=iAll+".intval($iAll).",iAllTime=iAllTime+".intval($chatime).",iAllPk=iAllPk+1" .",iWinAll=iWinAll+".$sScore[1]." where iSeqId =".$data[0]['iOpponentId']);

            $pkrecord_data = PkRecordModel::select('iUserId','iOpponentId','iResult')
                ->where('iSeqId',$iSeqId)
                ->first();
            if($pkrecord_data->iResult == '1-0'){
                $user_id = $this->userId;
                $user_name = $this->sUserName;
            }else{
                $user_id = $pkrecord_data->iOpponentId;
                $web_data = WebUserModel::select('sUserName')->where('iSeqId',$pkrecord_data->iOpponentId)->first();
                $user_name = isset($web_data->sUserName) ? $web_data->sUserName : '';
            }

            DB::table('banner')
                ->insertGetId(array(
                    "user_id"    => $user_id,
                    "user_name"  => $user_name,
                    "createTime" => date('Y-m-d H:i:s'),
                    "banner"     => '刚刚 '.urldecode($user_name).'  赢得了一场比赛，获得了'.$data[0]['sGold'].' 金币，快去发起挑战吧；',
                    'type'       => '2'
                ));


            return  response()->json(array(
                'code' => 200,
                'message' => '操作成功！！',
                'data'=>['uuid'=>$this->uuid,"iSeqId"=>$iSeqId]
            ));
            //添加pK 关联表


        }elseif($data[0]['iOpponentId']==$this->userId){

            if($data[0]['iStatus']==1){
                return  response()->json(array(
                    'code' => 400,
                    'message' => '请等待对局提交！！',
                ));
            }
            $sExt=json_decode($data[0]['sExt'],true);
            $sScore=explode(':',$sExt['sScore']);
            //var_dump($sExt);
            $sExt[$this->userId]=$sGan;
            $num = DB::table('pkrecord')
                ->where('iSeqId','=',$iSeqId)
                ->update(array("sExt"=>json_encode($sExt)));

            //操作用户表清杆数
            $bool = DB::table('webuser')->where(array("iSeqId"=>$this->userId))->increment("iQinggan",intval($sGan));

            $pkrecord_data = PkRecordModel::select('iUserId','iOpponentId','iResult')
                ->where('iSeqId',$iSeqId)
                ->first();
            if($pkrecord_data->iResult == '1-0'){
                $user_id = $this->userId;
                $user_name = $this->sUserName;
            }else{
                $user_id = $pkrecord_data->iOpponentId;
                $web_data = WebUserModel::select('sUserName')->where('iSeqId',$pkrecord_data->iOpponentId)->first();
                $user_name = isset($web_data->sUserName) ? $web_data->sUserName : '';
            }

            DB::table('banner')->insertGetId(array(
                "user_id"    => $user_id,
                "user_name"  => $user_name,
                "createTime" => date('Y-m-d H:i:s'),
                "banner"     => '刚刚 '.urldecode($user_name).'  赢得了一场比赛，获得了'.$data[0]['sGold'].' 金币，快去发起挑战吧；',
                'type'       => '2'
            ));


            return  response()->json(array(
                'code' => 200,
                'message' => '操作成功！！',
                'data'=>['uuid'=>$this->uuid,"iSeqId"=>$iSeqId],
            ));
        }
    }

    public function pkResultReply(Request $request){
        if($this->_defalutJson['code'] == -1 && empty($this->userId)) {
            return response()->json(array(
                'code' => 404,
                'message' => $this->_defalutJson['message'],
            ));
        }
        $iSeqId=  $request->input('iSeqId');//流水
        if(empty($iSeqId)){
            return  response()->json(array(
                'code' => 404,
                'message' => "缺少参数",
                "data"=>['uuid'=>$this->uuid]
            ));
        }
        $data = DB::table('pkrecord')
            ->where(array('iSeqId'=>$iSeqId,'iStatus'=>2))
            ->get()->toArray();
        $data=array_map('get_object_vars', $data);
        if(empty($data)){
            return  response()->json(array(
                'code' => 404,
                'message' => '对局不存在,请稍后重试！！',
            ));
        };

        if($data[0]['iUserId'] == $this->userId){
            $sExt=json_decode($data[0]['sExt'],true);
            $score=explode(':',$sExt['sScore']);
            if($score[0]>$score[1]){
                $iREslut=1;
            }else{
                $iREslut=-1;
            }
            //获取个人信息
            $myuser_data = WebUserModel::where('iUUID',$this->uuid)->first();
            $frienduser_data = WebUserModel::where('iSeqId',$data[0]['iOpponentId'])->first();
            //财富
            $arr2 = RelfriendModel::select("user_id")->where(array("master_user_id" => $this->userId))->get()->toArray();
            $arr2 = array_map('array_shift', $arr2);
            $arr2[''] = $this->userId;
            $user2 = GoldBeanModel::whereIn('iUserId', $arr2)
                ->orderBy("iNowGoldBean", "DESC")
                ->get()
                ->toArray();
            $caifupaiming='';
            $caifu='';
            foreach($user2 as $key=>$value){
                if($value['iUserId']==$this->userId){
                    $caifupaiming=$key+1;
                    $caifu=$value['iNowGoldBean'];
                }
            }
            $temgold='';
            $text='';
            $temuserid='';
            if($caifupaiming==1){
                $text="您的财富已达到：{$caifu}金币，在好友中排行第{$caifupaiming}位！";
            }else{
                $temgold=$user2[$caifupaiming-2]['iNowGoldBean']-$caifu;
                $temuserid=$user2[$caifupaiming-2]['iUserId'];
                $temuser_data = WebUserModel::where('iSeqId',$temuserid)->first();
                $text="您的财富已达到：{$caifu}金币，在好友中排行第{$caifupaiming}位！再赢得{$temgold}金币就可以超越好友".htmlspecialchars(urldecode($temuser_data->sUserName))."啦！";
            }


            $data=[
                "user"=>array(
                    array("name"=>htmlspecialchars(urldecode($myuser_data->sUserName)),"image"=>$myuser_data->sUserImage),
                    array("name"=>htmlspecialchars(urldecode($frienduser_data->sUserName)),"image"=>$frienduser_data->sUserImage)
                ),
                "result"=>$iREslut,
                "score"=>$sExt['sScore'],
                "caifu"=>$caifu,
                "text"=>$text,
                'uuid'=>$this->uuid,
            ];
              return  response()->json(array(
                  'code' => 200,
                  'message' => '查询成功！！',
                  'data'=>$data
              ));

        }elseif($data[0]['iOpponentId']==$this->userId){
            $sExt=json_decode($data[0]['sExt'],true);
            $score=explode(':',$sExt['sScore']);
            if($score[0] < $score[1]){
                $iREslut=1;
            }else{
                $iREslut=-1;
            }
            //获取个人信息
            $myuser_data = WebUserModel::where('iSeqId',$data[0]['iUserId'])->first();
            $frienduser_data = WebUserModel::where('iUUID',$this->uuid)->first();
            //财富
            $arr2 = RelfriendModel::select("user_id")->where(array("master_user_id" => $this->userId))->get()->toArray();
            $arr2 = array_map('array_shift', $arr2);
            $arr2[''] = $this->userId;
            $user2 = GoldBeanModel::whereIn('iUserId', $arr2)
                ->orderBy("iNowGoldBean", "DESC")
                ->get()
                ->toArray();
            $caifupaiming='';
            $caifu='';
            $temuserid='';
            foreach($user2 as $key=>$value){
                if($value['iUserId']==$this->userId){
                    $caifupaiming=$key+1;
                    $caifu=$value['iNowGoldBean'];
                }
            }
            $temgold='';
            $text='';
            if($caifupaiming==1){
                $text="您的财富已达到：{$caifu}金币，在好友中排行第{$caifupaiming}位！";
            }else{
                $temgold=$user2[$caifupaiming-2]['iNowGoldBean']-$caifu;
                $temuserid=$user2[$caifupaiming-2]['iUserId'];
                $temuser_data = WebUserModel::where('iSeqId',$temuserid)->first();
                $text="您的财富已达到：{$caifu}金币，在好友中排行第{$caifupaiming}位！再赢得{$temgold}金币就可以超越好友".htmlspecialchars(urldecode($temuser_data->sUserName))."啦！";
            }

            $data=[
                "user"=>array(
                    array("name"=>urldecode($myuser_data->sUserName),"image"=>$myuser_data->sUserImage),
                    array("name"=>urldecode($frienduser_data->sUserName),"image"=>$frienduser_data->sUserImage)
                ),
                "result"=>$iREslut,
                "score"=>$sExt['sScore'],
                "caifu"=>$caifu,
                "text"=>$text,
                'uuid'=>$this->uuid,
            ];
              return  response()->json(array(
                  'code' => 200,
                  'message' => '查询成功！！',
                  'data'=>$data
              ));
        }else{
            return  response()->json(array(
                'code' => 404,
                'message' => '对不起，找不到对局！！',
            ));
        }

    }

    //兑换
    public function exchange(Request $request){
        if($this->_defalutJson['code'] == -1 && empty($this->userId)) {
            return response()->json(array(
                'code' => 404,
                'message' => $this->_defalutJson['message'],
            ));
        }
        $golds =  $request->input('gold');//比分
        $goodsId = $request->input('goodsId');
        if(empty($golds)){
            return  response()->json(array(
                'code' => 404,
                'message' => "缺少参数",
                "data"=>['uuid'=>$this->uuid]
            ));
        }
        $gold=new GoldController();
        $gold->exChangeGold(-intval($golds),$this->userId,3,'兑换');


        //获取当前金豆数
        $now_gold_bean = GoldBeanModel::select('iNowGoldBean')->where('iUserId', $this->userId)->first();
        $gold_bean_num = 0;
        if (!empty($now_gold_bean) && $now_gold_bean->iNowGoldBean > 0) {
            $gold_bean_num = $now_gold_bean->iNowGoldBean;
        }

        $bool = DB::table('goldexchange')
            ->insertGetId(array(
            "iUserId"=>$this->userId,
            "iExGold"=>-intval($golds),
            "dtModifyTime"=>date("Y-m-d H:i:s"),
            'sRemark'=>'兑换'
            ));
        $goodsName = '';
        switch ($goodsId){
            case 1:
                $goodsName = "一小时免费券";
                break;
            case 2:
                $goodsName = "可口可乐";
                break;
            case 3:
                $goodsName = "矿泉水";
                break;
            case 4:
                $goodsName = "一小时练球卡";
                break;

        }

        DB::table('banner')
            ->insertGetId(array(
                "user_id"    => $this->userId,
                "user_name"  => $this->sUserName,
                "createTime" => date('Y-m-d H:i:s'),
                "banner"     => '刚刚 '.urldecode($this->sUserName).' 消耗了'.$golds.' 金币兑换了 '.$goodsName.'，还不快去赢金币换奖；',
                'type'       => '1'
            ));

        return  response()->json(array(
            'code' => 200,
            'message' => "操作成功",
            "data"=>[
                'uuid'=>$this->uuid,
                'nowGold'=>$gold_bean_num,
            ]
        ));
    }
    public function checkNowPk(){

        if($this->_defalutJson['code'] == -1 && empty($this->userId)) {
            return response()->json(array(
                'code' => 404,
                'message' => $this->_defalutJson['message'],
            ));
        }
        $time=date("Y-m-d H:i:s",time()-120*60);

        //查询数据
        $pkrecord = PkRecordModel::select('iSeqId','iUserId','iOpponentId','dtStartTime','sPkType','sGold','sCode')
            ->whereRaw("(iUserId={$this->userId} and iOpponentId!=0 and iStatus=1 and dtStartTime!='' and dtStartTime > '".$time."')")
            ->orWhereRaw("(iOpponentId={$this->userId} and iOpponentId!=0 and iStatus=1 and dtStartTime!='' and dtStartTime > '".$time."')")
            ->orderBy("dtStartTime", "DESC")
            ->get()
            ->toArray();
        if(empty($pkrecord)){
            return response()->json(array(
                'code' => 404,
                'message' => '没有中断的对局',
                'data'=>array(
                    'uuid'=>$this->uuid,
                    'result'=>0,

                )
            ));
        }else{
            $data=$pkrecord[0];
            $marsterone=WebUserModel::where('iSeqId',$data['iUserId'])->first();
            $data['user']['one']=array('sUserName'=>empty($marsterone->sUserName) ? '' : urldecode($marsterone->sUserName),
                'sUserImage'=>empty($marsterone->sUserImage) ? '' : urldecode($marsterone->sUserImage)
            );
            $marstertwo=WebUserModel::where('iSeqId',$data['iOpponentId'])->first();
            $data['user']['two']=array('sUserName'=>empty($marstertwo->sUserName) ? '' : urldecode($marstertwo->sUserName),
                'sUserImage'=>empty($marstertwo->sUserImage) ? '' : urldecode($marstertwo->sUserImage)
            );
            if($this->userId==$data['iUserId']){

                $data['sInitiative']=1;
            }else{

                $data['sInitiative']=0;
            }
            return response()->json(array(
                'code' => 200,
                'message' => '存在对局',
                'data'=>array(
                    'uuid'=>$this->uuid,
                    'result'=>1,
                    'list'=>$data,
                )
            ));
        }
    }
}